<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { sysUserQueryRoleByUserId } from '@/api/backstage'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => undefined
  }
})
const form = reactive({
  roles: [],
  orgId: '',
  userId: ''
})
const rules = reactive({
  roles: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log('formData', formData)
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    form.orgId = currentRow.orgId
    form.userId = currentRow.id

    setValues(form)
  },
  {
    deep: true,
    immediate: true
  }
)
const formSchema = reactive<FormSchema[]>([
  {
    field: 'roles',
    component: 'Select',
    colProps: {
      span: 24
    },
    label: '角色',
    componentProps: {
      placeholder: '请选择角色',
      multiple: true,
      filterable: true,
      props: {
        label: 'name',
        value: 'id'
      }
    },
    optionApi: async () => {
      const res = await sysUserQueryRoleByUserId({
        pageSize: 1000,
        pageNum: 1,
        userId: form.userId
      })
      const checkRole = res.data.records
        .filter((item: any) => item.owned)
        .map((item: any) => item.id)
      form.roles = checkRole || []
      setValues(form)
      return res.data.records || []
    }
  }
])

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
